﻿using Cofe.Core.Entry;
using Cofe.Core.Interfaces;
using Cofe.Core.Property;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cofe.Core.Dynamic
{
    /// <summary>
    /// If the input is IEntryLinkPropertyProvider, query it's linked entry and try to convert from that
    /// </summary>
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFE-1)] //This is after CofeInterfaceProvider is called.
    public class CofeEntryLinkInterfaceProvider : IDynamicPropertyInterfaceProvider
    {
        public bool CanCastAs<T>(IPropertyHost input) where T : IDynamicInterface<IPropertyHost>
        {
            if (input.Behaviors.IsPropertySupported(CofeEntryLinkProperties.LinkedEntryPH))
            {
                return EntryConstructor.ConstructEntryAsync(                        
                            input.Behaviors.GetProperty(CofeEntryLinkProperties.LinkedEntryPH).ValueAs<IPropertyHost>()).Result.Is<T>();
                
            }
            return false;
        }

        public T CastAs<T>(IPropertyHost input) where T : IDynamicInterface<Property.IPropertyHost>
        {
            if (CanCastAs<T>(input))
            {
                return EntryConstructor.ConstructEntryAsync(                        
                            input.Behaviors.GetProperty(CofeEntryLinkProperties.LinkedEntryPH).ValueAs<IPropertyHost>()).Result.As<T>();

            }
            return default(T);
        }

        #region Data

        private IEntryConstructor _entryConstructor = null;

        #endregion

        #region Public Properties

        public IEntryConstructor EntryConstructor
        {
            get { return _entryConstructor ?? CofeServices.ServiceLocater.FindService<IEntryConstructor>(); }
            set { _entryConstructor = value; }
        }

        public Type[] CastableInterfaces
        {
            get { return new Type[] { typeof(IEntryLink) }; }
        }

        public Type[] CastableContainers
        {
            get { return new Type[] { typeof(EntryLink) }; }
        }

        #endregion







      
    }
}
